import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild} from '@angular/router';
import {NavController} from '@ionic/angular';
import {Storage} from '@ionic/storage';
import {AppConfig} from '../common/app-config.enum';

/**
 * 进行登录状态拦截（只针对子路由）
 */
@Injectable({
  providedIn: 'root'
})
export class LoginGuard implements CanActivateChild {

  constructor(private navCtrl: NavController,
              private storage: Storage
  ) {
  }

  async canActivateChild(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {
    // 获取用户信息
    const userInfo = await this.storage.get(AppConfig.USER_INFO);
    if (userInfo && userInfo[AppConfig.USER_INFO_KEY]) {
      return true;
    }
    this.navCtrl.navigateForward(['/login']);
    return false;
  }
}
